package com.iaiai.cobra.core.config.intercepter.req;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Package: com.txt.bamboo.admin.intercepter.wrapper
 * Author: iaiai
 * Create Time: 2019/12/24 8:50 下午
 * QQ: 176291935
 * Url: http://iaiai.iteye.com
 * Email: 176291935@qq.com
 * Description:
 */
@Slf4j
@Component
@WebFilter(filterName = "HttpServletRequestFilter", urlPatterns = "/")
public class ReplaceStreamFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(servletRequest instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            if(httpServletRequest.getHeader("Content-Type")==null
                    || !httpServletRequest.getHeader("Content-Type").startsWith("multipart/form-data")) {
                ServletRequest requestWrapper = new RequestWrapper(httpServletRequest);
                filterChain.doFilter(requestWrapper, servletResponse);
            }else{
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

}
